import { useParams, Link } from "react-router-dom"
import { message, Button, Spin, Space } from 'antd'
import { useEffect, useState } from "react"

import { queryDetail } from "../../apis/model"

import DetailHeader from "../../components/DetailHeader"
import ModelerVersionPicker from "../../components/ModelerVersionPicker"
import ModelerSetNewVersion from "../../components/ModelerSetNewVersion"
import useModelVersion from "../../hooks/useModelVersion"
import ProcessPreview from "../../components/ProcessDesigner/preview/ProcessPreview"


const ModelerProcessDesign = () => {

  const { id: modelId } = useParams()
  const [loading, setLoading] = useState(false)
  const [detail, setDetail] = useState({})

  const doQueryDetail = async (versionId) => {
    if (!loading) {
      setLoading(true)
      try {
        const data = await queryDetail(modelId, versionId)
        setDetail(data)

        // 设置当前版本
        if (!versionId) {
          setReleaseVersion(data.version)
        }

      } catch (error) {
        message.error('查询失败')
      }
      setLoading(false)
    }
  }

  // 使用模型版本钩子
  const {
    versions,
    doQueryVersions,
    setReleaseVersion,
    curVersion,
    curVerionId,
    isReleaseVersion,
    handleChangeVersion
  } = useModelVersion({
    modelId: modelId,
    changeVersionAction: (versionItem, releaseVersion) => {
      if (versionItem.version !== releaseVersion) {
        doQueryDetail(versionItem.id)
      } else {
        doQueryDetail()
      }
    }
  })

  useEffect(() => {
    if (modelId) {
      doQueryDetail()
    }
  }, [modelId])

  const renderHeaderButtons = () => {
    return <Space>
      {
        !!detail.name && (
          isReleaseVersion ?
            <Link to={`/modeler/processes/design/${modelId}`}>
              <Button type="primary">可视化编辑</Button>
            </Link>
            :
            <ModelerSetNewVersion
              modelId={modelId}
              versionId={curVerionId}
              onSuccess={() => {
                doQueryDetail()
                doQueryVersions()
              }}
            ></ModelerSetNewVersion>
        )
      }
    </Space>
  }

  const renderHeaderTitle = () => {
    return <div style={{
      display: "flex",
      alignItems: 'center'
    }}>
      <b style={{ fontSize: 18 }}>{detail.name}</b>
      <ModelerVersionPicker
        versions={versions}
        value={curVersion}
        onChange={handleChangeVersion}
      ></ModelerVersionPicker>
    </div>
  }

  return <Spin spinning={loading} wrapperClassName="page-wrap">
    <DetailHeader
      title={renderHeaderTitle()}
      extra={renderHeaderButtons()}
    ></DetailHeader>
    <div className="page-body">
      <ProcessPreview
        modelId={modelId}
        versionId={isReleaseVersion ? null : curVerionId}
      />
    </div>
  </Spin>
}

export default ModelerProcessDesign